# coding: utf-8
from typing import List, Tuple

from PySide6.QtCore import QEvent, QPoint, Qt
from PySide6.QtGui import QEnterEvent, QResizeEvent
from PySide6.QtWidgets import QHBoxLayout, QFileDialog
from qfluentwidgets import TransparentToolButton, FluentIcon as FIF, ToolTipFilter, RoundMenu, Action, BodyLabel

from common import workerRequest, cfg, getTimestamp, signalBus
from components import ZoomImageLabel, SideWidget, Alert
from server.api import download_image


class ToolTipTransparentToolButton(TransparentToolButton):
    def _postInit(self):
        self.installEventFilter(ToolTipFilter(self))


class ToolBar(SideWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout(self)
        self._title = ''
        self.pixels = []
        self.menu = None

        self.titleLabel = BodyLabel('标题', self)
        self.downloadButton = ToolTipTransparentToolButton(FIF.CLOUD_DOWNLOAD, self)
        self.saveAsButton = ToolTipTransparentToolButton(FIF.SAVE_AS, self)
        self.moreButton = ToolTipTransparentToolButton(FIF.MORE, self)

        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.horizontalLayout.addWidget(self.titleLabel, 1, Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addWidget(self.downloadButton)
        self.horizontalLayout.addWidget(self.saveAsButton)
        self.horizontalLayout.addWidget(self.moreButton)

        self.downloadButton.setToolTip('快速下载')
        self.saveAsButton.setToolTip('另存为')
        self.moreButton.setToolTip('更多')
        self.moreButton.setVisible(False)
        self.installEventFilter(ToolTipFilter(self))

        self.moreButton.clicked.connect(self.onMoreButtonClicked)

    def onMoreButtonClicked(self):
        if not self.pixels:
            return
        self.menu = RoundMenu('', self)
        for (text, url) in self.pixels:
            text = text.center(11)
            self.menu.addAction(
                Action(text, self.menu, triggered=lambda: self.downloadImage(url)))

        self.menu.closedSignal.connect(self.onMenuClosed)
        x = (self.moreButton.width() - self.menu.width()) // 2 + 10
        pos = self.moreButton.mapToGlobal(QPoint(x, self.moreButton.height()))
        self.menu.exec(pos)

    def onMenuClosed(self):
        self.hide()
        self.menu = None

    def setPixels(self, pixels: List[Tuple[str, str]]):
        self.pixels = pixels
        if not pixels:
            self.moreButton.setVisible(False)
        else:
            self.moreButton.setVisible(True)

    def downloadImage(self, url: str, filename: str = None):
        if not filename:
            download_folder = cfg.get(cfg.downloadFolder)
            filename = f'{download_folder}/{getTimestamp()}.png'
        Alert.info('添加到下载列表')
        workerRequest(download_image, url, filename, slot=self.onDownloadImageFinished)

    def onDownloadImageFinished(self, filename: str):
        Alert.success(f'下载完成：{filename}')

    def setTitle(self, title: str):
        self._title = title
        self.setToolTip(title)
        self.titleLabel.setText(title)
        self.titleLabel.adjustSize()

    def title(self) -> str:
        return self._title

    def resizeEvent(self, event: QResizeEvent) -> None:
        super().resizeEvent(event)
        title = self.titleLabel.fontMetrics().elidedText(self._title, Qt.TextElideMode.ElideRight,
                                                         self.titleLabel.width())
        self.titleLabel.setText(title)


class WallpaperCard(ZoomImageLabel):
    def _postInit(self):
        super()._postInit()
        self.max_url = ''
        self.title = ''
        self.description = ''

        self.toolBar = ToolBar(self)
        self.toolBar.setDirection(SideWidget.Top)
        self.toolBar.hide()
        self.adjustBar()

        self.toolBar.downloadButton.clicked.connect(lambda: self.toolBar.downloadImage(self.url))
        self.toolBar.saveAsButton.clicked.connect(self.onSaveAsButtonClicked)

        self.clicked.connect(self.onCardClicked)

    def onCardClicked(self):
        if self.max_url:
            signalBus.showImageSignal.emit(self.title, self.description, self.max_url)

    def adjustBar(self):
        self.toolBar.setGeometry(0, 0, self.width(), 50)

    def enterEvent(self, event: QEnterEvent) -> None:
        super().enterEvent(event)
        self.toolBar.show()

    def leaveEvent(self, event: QEvent) -> None:
        super().leaveEvent(event)
        if not self.toolBar.menu:
            self.toolBar.hide()

    def resizeEvent(self, event: QResizeEvent) -> None:
        super().resizeEvent(event)
        self.adjustBar()

    def setMenuData(self, pixels: List[Tuple[str, str]]):
        self.toolBar.setPixels(pixels)

    def setTitle(self, title: str):
        self.title = title
        self.toolBar.setTitle(title)

    def onSaveAsButtonClicked(self):
        filename, _ = QFileDialog.getSaveFileName(self, '另存为', '', '图片文件(*.jpg *.png)')
        if not filename:
            return
        self.toolBar.downloadImage(self.url, filename)

    def setMaxUrl(self, url: str):
        self.max_url = url

    def setDescription(self, description: str):
        self.description = description


if __name__ == '__main__':
    import sys
    from PySide6.QtWidgets import QApplication

    app = QApplication(sys.argv)
    card = WallpaperCard()
    card.setImage(r"G:\手机\壁纸\77FAA7D1814A28F37E02273DB0E72041.jpg")
    card.setMenuData(
        [('下载', 'https://www.baidu.com'), ('另存为', 'https://www.google.com'), ('更多', 'https://www.bing.com')])
    card.move(100, 100)
    card.show()
    sys.exit(app.exec())
